import { Text, View } from '@tarojs/components';
import theme from '@/theme';
import { ComponentProps, useMemo, useState } from 'react';
import '../index.scss';
import classNames from 'classnames';
import { Grid, Icon } from 'pd-taro-ui';
import { pxTransform } from '@tarojs/taro';
import dayjs, { Dayjs } from 'dayjs';
import { isInTimeRange } from '../utils';
import CalendarItem from '../CalendarItem';
import type { CalendarRenderItem } from '../type';

interface YearViewProps {
  placeholder?: string;
  /** day单选， range日期范围(start,end) ,  默认day */
  mode?: 'day' | 'range';
  value?: string | string[];
  onChange?: (value: YearViewProps['value']) => void;
  onBlur?: any;
  staticed?: boolean;
  disabled?: boolean;
  clearable?: boolean;
  className?: string;
  // minDate?: string;
  // maxDate?: string;
  // disabledDate?: (date: Dayjs) => boolean;
}

const YearView = ({
  onChange,
  value,
  disabled,
  staticed,
  onBlur,
  clearable = false,
  placeholder,
  className,
  // disabledDate,
  // minDate,
  // maxDate,
  mode = 'day',
}: YearViewProps) => {
  const values = useMemo(() => {
    if (!value) {
      return [];
    }
    if (Array.isArray(value)) {
      return value;
    }
    return [value];
  }, [value]);
  /** 当前选中的年月 */
  const [yearMonth, setYearMonth] = useState(dayjs(dayjs().format('YYYY').slice(0, 3) + '0-01-01'));
  /** 临时用，给range mode使用 */
  const [tempRange, setTempRange] = useState<string[]>([]);
  // console.log('tempRange', tempRange);
  // console.log('values', values);

  const prevBig = () => {
    setYearMonth(yearMonth.subtract(10, 'year'));
  };

  const nextBig = () => {
    setYearMonth(yearMonth.add(10, 'year'));
  };

  const items = useMemo(() => {
    const list: CalendarRenderItem[] = [];
    // 2020-2029 ,  前后各+1，凑够12个
    for (let i = -1; i < 11; i++) {
      let itemDisabled = false;
      let itemActive = false;
      let itemActiveFirst = false;
      let itemActiveLast = false;
      const value0 = values[0];
      const value1 = values[1];
      const date = yearMonth.add(i, 'year');
      if (mode === 'day') {
        if (value0 && dayjs(value0).format('YYYY') === date.format('YYYY')) {
          itemActive = true;
        }
      } else if (mode == 'range') {
        if (tempRange.length) {
          if (tempRange.length == 1) {
            if (tempRange[0] && dayjs(tempRange[0]).format('YYYY-01-01') === date.format('YYYY-01-01')) {
              itemActive = true;
              itemActiveFirst = true;
            }
          } else {
            const data = isInTimeRange(date, tempRange[0], tempRange[1]);
            itemActive = data.active;
            itemActiveFirst = data.activeFirst;
            itemActiveLast = data.activeEnd;
          }
        } else {
          const data = isInTimeRange(date, value0, value1);
          itemActive = data.active;
          itemActiveFirst = data.activeFirst;
          itemActiveLast = data.activeEnd;
        }
      }
      list.push({
        text: date.format('YYYY'),
        value: date.format('YYYY'),
        disabled: itemDisabled,
        active: itemActive,
        activeFirst: itemActiveFirst,
        activeLast: itemActiveLast,
      });
    }
    // console.log('yearView list', list);
    return list;
  }, [mode, tempRange, values, yearMonth]);

  const onClickItem = (item: CalendarRenderItem) => {
    if (mode === 'day') {
      onChange?.(item.value);
    } else if (mode === 'range') {
      if (!tempRange.length) {
        setTempRange([item.value]);
      } else if (tempRange.length === 1) {
        let newList: string[] = [];
        const pre = dayjs(tempRange[0]);
        if (pre.startOf('day').valueOf() === dayjs(item.value).startOf('day').valueOf()) {
          newList = [item.value, item.value];
        } else {
          if (pre.startOf('day').valueOf() > dayjs(item.value).startOf('day').valueOf()) {
            newList = [item.value, tempRange[0]];
          } else {
            newList = [tempRange[0], item.value];
          }
        }
        setTempRange(newList);
        onChange?.(newList);
      } else if (tempRange.length === 2) {
        setTempRange([]);
        onChange?.([]);
      }
    }
  };

  const headerText = useMemo(() => {
    return `${yearMonth.format('YYYY年')} - ${yearMonth.add(10, 'year').format('YYYY年')}`;
  }, [yearMonth]);

  if (staticed) {
    return <View className='pd-calendar--static'>{value}</View>;
  }
  return (
    <View className={classNames({ 'pd-calendar': true, 'pd-calendar--disabled': disabled }, className)}>
      <View className='pd-calendar__head'>
        <Icon name='left-double-arrow' className='pd-calendar__head__icon' onClick={prevBig} style={{ marginRight: pxTransform(10) }} />
        <Text className='pd-calendar__head__text'>{headerText}</Text>
        <Icon name='right-double-arrow' className='pd-calendar__head__icon' onClick={nextBig} style={{ marginLeft: pxTransform(10) }} />
      </View>
      <View className='pd-calendar__list'>
        <Grid column={3}>
          {items.map(item => (
            <CalendarItem
              key={'day_' + item}
              disabled={item.disabled}
              active={item.active}
              activeFirst={item.activeFirst}
              activeLast={item.activeLast}
              onClick={() => onClickItem(item)}>
              {item.text}
            </CalendarItem>
          ))}
        </Grid>
      </View>
    </View>
  );
};

export default YearView;
